/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Sablony;

import java.io.File;
import java.util.TreeSet;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

/**
 *
 * @author MartinaHlinková
 */
public class SablonaZamestnancov implements Comparable<SablonaZamestnancov> {
   private String nazov;
   private TreeSet<Zamestnanec> zamestnanciVSablone;
   
   
   public SablonaZamestnancov(String nazov){
       this.nazov = nazov;
       this.zamestnanciVSablone = new TreeSet<Zamestnanec>();
   }
   
   public String getNazov(){
       return this.nazov;
   }
   
   public TreeSet<Zamestnanec> getZamestnanciVSablone(){
       return this.zamestnanciVSablone;
   }
   
   public boolean pridajZamestnanca(int id, String meno, String priezvisko, String titul, Sablony.Pohlavie pohlavie, Sablony.Funkcia funkcia, Sablony.TypZamestnanca typ,Sablony.SiloveUlohy sila){
       if(meno == null || priezvisko == null || pohlavie == null || funkcia == null || typ == null || sila == null)return false;
       if(id < 10 || id > 99)return false;
       Sablony.Zamestnanec novy = new Zamestnanec(id,meno,priezvisko,titul,funkcia,pohlavie,sila,typ);
       if(this.zamestnanciVSablone.contains(novy) == true) return false;
       return this.zamestnanciVSablone.add(novy);

   }
   
   public boolean pridajZamestnanca(Sablony.Zamestnanec novy){
       if(novy.getIDZamestnanca() < 10 || novy.getIDZamestnanca() > 99) return false;
       if(novy.getMenoZamestnanca() == null || novy.getPriezviskoZamestnanca() == null) return false;
       if(novy.getFunkciaZamestnanca() == null || novy.getPohlavieZamestnanca() == null || novy.getSilaZamestnanca() == null || novy.getTypZamestnanca() == null) return false;
       if(this.zamestnanciVSablone.contains(novy) == true) return false;
       return this.zamestnanciVSablone.add(novy);
   }
   
   public boolean odoberZamestnanca(int ID){
        for(Zamestnanec iterator: this.zamestnanciVSablone){
           if(iterator.getIDZamestnanca() == ID){
               this.zamestnanciVSablone.remove(iterator);
               return true;
           }
        }
        return false;
    }
   
    public boolean odoberZamestnanca(Sablony.Zamestnanec zamestnanec ){
        if(zamestnanec == null){
            return false;
        }
          if(this.zamestnanciVSablone.contains(zamestnanec)){
              this.zamestnanciVSablone.remove(zamestnanec);
              return true;
          }
        return false;
    }
    
    public String[][] sablonaZamestnancovToArray(){
        int pocet = this.zamestnanciVSablone.size();
        String[][] sablonaArray = new String[pocet][8];
        int i = 0;
        for(Zamestnanec iterator: this.zamestnanciVSablone){
            sablonaArray[i] = iterator.zamestnanecToArray();
            i++;
        }
        return sablonaArray;
    }
    
    public int pocetZamestnancov(){
        return this.zamestnanciVSablone.size();
    }
    
    public Sablony.Zamestnanec najdiZamestnancaPodlaID(int id){
        if( id < 10 || id > 99)return null;
        for(Zamestnanec iterator:this.zamestnanciVSablone){
            if(iterator.getIDZamestnanca() == id){
                return iterator;
            }
        }
        return null;
    }
    
    public void novaXMLSablona(){
        try {
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 
		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("sablonaZamestnancov");
		doc.appendChild(rootElement);
                for(Zamestnanec iterator: this.zamestnanciVSablone){
                    Element zamestnanec = iterator.zamestnanecToElement(doc);
                    //Element zamestnanec = doc.createElement("zamestnanec");
                    rootElement.appendChild(zamestnanec);
                
                  
                }
                // write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(this.nazov+".xsz"));
                
                transformer.transform(source, result);
 
		
        }catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	  } catch (TransformerException tfe) {
		tfe.printStackTrace();
	  }
    }
    
     public static SablonaZamestnancov nacitajSablonu(File xml){
         if(xml == null || xml.isDirectory() || !xml.isFile()) return null;
         try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xml);
            doc.getDocumentElement().normalize();
            
            NodeList nList = doc.getElementsByTagName("zamestnanec"); // list s uzlamiZamestnancov
            
             // ziskanie mena sablony
                String meno = xml.getPath();
                if(meno == null)return null;
                
                char data[] = {'\\', '\\'};
                String strRegex = new String(data);
                String str[] = meno.split(strRegex);
                
                meno = str[str.length-1];
                
                char data1[] = {'\\','.', };
                strRegex = new String(data1);
                str = meno.split(strRegex);
                if(str == null || str.length != 2) return null;
                meno = str[0];
                
                
                 // vytvorenie prazdnej sablony
                SablonaZamestnancov nacitanaSablona = new SablonaZamestnancov(meno);
                
                for (int i = 0; i < nList.getLength(); i++) { //for pre kazdy uzol zamestnanca
 
                    Node nNode = nList.item(i);
 
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
			Element eElement = (Element) nNode;
                        
                        int id = Integer.parseInt(eElement.getAttribute("id"));
                        String menoZ = eElement.getElementsByTagName("meno").item(0).getTextContent();
                        String priezviskoZ = eElement.getElementsByTagName("priezvisko").item(0).getTextContent();
                        String titulZ = eElement.getElementsByTagName("titul").item(0).getTextContent();
                        
                        String funkciaZ = eElement.getAttribute("funkcia");
                        Sablony.Funkcia funkcia = null;
                        final Sablony.Funkcia[] funkcie = Sablony.Funkcia.values();
                        for(Sablony.Funkcia iterator: funkcie){
                            if(iterator.toString().equals(funkciaZ)){
                                funkcia = iterator;
                            }
                        }
                        
                        String pohlavieZ = eElement.getAttribute("pohlavie");
                        Sablony.Pohlavie pohlavie = null;
                        final Sablony.Pohlavie[] pohlavia = Sablony.Pohlavie.values();
                        for(Sablony.Pohlavie iterator: pohlavia){
                            if(iterator.toString().equals(pohlavieZ)){
                                pohlavie = iterator;
                            }
                        }
                        
                        String silaZ = eElement.getAttribute("sila");
                        Sablony.SiloveUlohy sila = null;
                        final Sablony.SiloveUlohy[] sily = Sablony.SiloveUlohy.values();
                        for(Sablony.SiloveUlohy iterator: sily){
                            if(iterator.toString().equals(silaZ)){
                                sila = iterator;
                            }
                        }
                        
                        String typZ = eElement.getAttribute("typZamestnanca");
                        Sablony.TypZamestnanca typ = null;
                        final Sablony.TypZamestnanca[] typy = Sablony.TypZamestnanca.values();
                        for(Sablony.TypZamestnanca iterator: typy){
                            if(iterator.toString().equals(typZ)){
                                typ = iterator;
                            }
                        }
                        
                        Sablony.Zamestnanec nacitanyZamestnanec = new Zamestnanec(id,menoZ,priezviskoZ,titulZ,funkcia,pohlavie,sila,typ);
                        NodeList listNepritomnosti = eElement.getElementsByTagName("nepritomnost");// uzly nepritomnosti zamestnanca
                        
                        for (int j = 0; j < listNepritomnosti.getLength(); j++) {// for pre kazdy uzol nepritomnosti
                            InformacnaStruktura.Den den = null;
                            InformacnaStruktura.CasBezDatumu casOd, casDo;
                            Node nodeNepritomnost = listNepritomnosti.item(j);
                            
                            if (nodeNepritomnost.getNodeType() == Node.ELEMENT_NODE) {
                                Element eNepritomnost = (Element) nodeNepritomnost;
                                
                                Node nodeOD = eNepritomnost.getElementsByTagName("OD").item(0);
                                Node nodeDO = eNepritomnost.getElementsByTagName("DO").item(0);
                                Node nodeDen = eNepritomnost.getElementsByTagName("den").item(0);
                                
                                casOd = new InformacnaStruktura.CasBezDatumu(
                                        Integer.parseInt(((Element)nodeOD).getAttribute("hodina"))
                                        , Integer.parseInt(((Element)nodeOD).getAttribute("minuta")));
                                casDo = new InformacnaStruktura.CasBezDatumu(
                                        Integer.parseInt(((Element)nodeDO).getAttribute("hodina"))
                                        , Integer.parseInt(((Element)nodeDO).getAttribute("minuta")));
                                String denString = ((Element)nodeDen).getTextContent();
                                final InformacnaStruktura.Den[] dni = InformacnaStruktura.Den.values();
                                for(InformacnaStruktura.Den iterator: dni){
                                    if(iterator.toString().equals(denString)){
                                        den = iterator;
                                    }
                                }
                                nacitanyZamestnanec.pridajNepritomnost(den,casOd, casDo);
                            }
                       }// for pre kazdy uzol nepritomnosti
                        nacitanaSablona.pridajZamestnanca(nacitanyZamestnanec);
                    }// if element node
                }//for pre kazdy uzol zamestnanca
                 return nacitanaSablona;
                   
         }catch (Exception e) {
            //e.printStackTrace();
             return null;
         } 
        
     }

    public int compareTo(SablonaZamestnancov o) {
       return this.getNazov().compareTo(o.getNazov());
    }

    @Override
    public int hashCode() {
        int hash = 3;
        String nazovHash = this.getNazov();
        for(int i = 0; i< nazovHash.length(); i++){
            hash = hash*nazovHash.charAt(i)%Integer.MAX_VALUE;
        }
        return hash;
    }
    
    @Override
     public boolean equals(Object o){
        if(o == this){
            return true;
        }
        if(o instanceof SablonaZamestnancov == false){
            return false;
        }
        boolean rovnake = (this.getNazov().equals(((SablonaZamestnancov) o).getNazov()));
        return rovnake;
    }
}
